package auth

import (
    "crypto/sha256"
    "encoding/hex"
    "sync"
)

type Authenticator interface {
    Authenticate(username, password string) bool
    AddUser(username, password string) error
    RemoveUser(username string) error
}

type SimpleAuthenticator struct {
    users map[string]string // username -> hashed password
    mu    sync.RWMutex
}

func NewSimpleAuthenticator() *SimpleAuthenticator {
    return &SimpleAuthenticator{
        users: make(map[string]string),
    }
}

func (a *SimpleAuthenticator) Authenticate(username, password string) bool {
    if username == "" {
        return true // 允许匿名连接
    }
    
    a.mu.RLock()
    defer a.mu.RUnlock()
    
    hashedPassword, exists := a.users[username]
    if !exists {
        return false
    }
    
    return hashedPassword == a.hashPassword(password)
}

func (a *SimpleAuthenticator) AddUser(username, password string) error {
    a.mu.Lock()
    defer a.mu.Unlock()
    
    a.users[username] = a.hashPassword(password)
    return nil
}

func (a *SimpleAuthenticator) RemoveUser(username string) error {
    a.mu.Lock()
    defer a.mu.Unlock()
    
    delete(a.users, username)
    return nil
}

func (a *SimpleAuthenticator) hashPassword(password string) string {
    hash := sha256.Sum256([]byte(password))
    return hex.EncodeToString(hash[:])
}
